package com.itheima.algorithm.stack;

/**
 * @author: TylerZhong
 * @description:
 */
public class E01Leetcode20 {
    public boolean isValid(String s) {
        ArrayStack<Character> arrayStack = new ArrayStack<>(s.length());
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                arrayStack.push(')');
            } else if (c == '[') {
                arrayStack.push(']');
            } else if (c == '{') {
                arrayStack.push('}');
            } else {
                if (!arrayStack.isEmpty() && c == arrayStack.peek()) {
                    arrayStack.pop();
                } else {
                    return false;
                }
            }
        }
        return arrayStack.isEmpty();
    }

    /**
     * 遇到左括号，把要配对的右括号放入栈顶
     * 遇到右括号，把它与栈顶元素对比
     * 若相等，栈顶元素弹出，继续对比下一组
     * 若不等，无效括号直接返回 false
     * @param args
     */
    public static void main(String[] args) {
        E01Leetcode20 s = new E01Leetcode20();
        System.out.println(s.isValid("([{}])"));
        System.out.println(s.isValid("()[]{}"));
        System.out.println(s.isValid("()"));
        System.out.println("-----------------------------------------");
        System.out.println(s.isValid("[)"));
        System.out.println(s.isValid("([)]"));
        System.out.println(s.isValid("([]"));
        System.out.println(s.isValid("("));
        System.out.println("-----------------------------------------");
        System.out.println(s.isValid(")("));
        System.out.println(s.isValid("]"));
    }
}
